﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Designtime.Metadata;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Designer.Views
{
    public static class CheckInThread
    {
        private static List<SolutionTreeViewNode> _nodeList;

        private static bool s_isRunning = false;
        private static Thread s_thread;
        private static Action<Guid, string, int, int> s_progress;
        private static Action<bool, int, int> s_completed;
        private static List<SolutionTreeViewNode> s_nodeList;

        /// <summary>
        /// solutiontreeviewNode状态在线程中修改
        /// </summary>
        /// <param name="nodeList"></param>
        /// <param name="progress">项目ID, 项目名称，签入进度，总数量</param>
        /// <param name="completed">是否出现错误，成功数量，总数量</param>
        public static bool Start(List<SolutionTreeViewNode> nodeList, Action<Guid, string, int, int> progress, Action<bool, int, int> completed)
        {
            if (s_isRunning)
            {
                return false;
            }

            s_nodeList = nodeList;
            s_progress = progress;
            s_completed = completed;
            s_isRunning = true;
            s_thread = new Thread(Running);
            s_thread.Start();
            return true;
        }

        public static void Stop()
        {
            if (s_isRunning)
            {
                s_thread.Abort();
                s_isRunning = false;
                s_thread = null;
            }
        }

        private static void Running()
        {
            int total = s_nodeList.Count;
            int progress = 0;
            bool hasError = false;

            CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DesignServiceClient dsClient =
                CPPEI.Coolzon.ServiceProxy.DesignServiceProxyManager.Create();

            string workspacePath = UIContext.Current.LocalWorkSpace.LocalPath;
            Guid solutionId = UIContext.Current.CurrentSolution.ID;
            //检查服务器给的项目是否在本地都有，或者是否最新
            for (int index = 0; index < s_nodeList.Count; index++)
            {
                SolutionTreeViewNode tvNode = s_nodeList[index];

                CPPEI.Coolzon.ServiceProxy.DesignServiceRef.CheckInRequest checkInRequest = new ServiceProxy.DesignServiceRef.CheckInRequest();
                checkInRequest.Token = UIContext.Current.Token;
                try
                {
                    string filePath = string.Empty;
                    if(tvNode.NodeType == NodeType.Solution)
                    {
                        filePath = LocalStorage.GetSolutionFileAbsolutePath(workspacePath, solutionId);
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.Solution;
                    }
                    else if(tvNode.NodeType == NodeType.Scene)
                    {
                        filePath = LocalStorage.GetSceneFileAbsolutePath(workspacePath, solutionId, tvNode.ID);
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.Scene;
                    }
                    else if(tvNode.NodeType == NodeType.Folder)
                    {
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.Folder;
                    }
                    else if (tvNode.NodeType == NodeType.Template)
                    {
                        filePath = LocalStorage.GetSceneFileAbsolutePath(workspacePath, solutionId,tvNode.ParentID);
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.Template;
                    }
                    else if (tvNode.NodeType == NodeType.StaticDataSource)
                    {
                        filePath = LocalStorage.GetStaticDataSourceAbsolutePath(workspacePath, solutionId, tvNode.ID);
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.StaticDataSource;
                    }
                    else
                    {
                        filePath = LocalStorage.GetResourceFileAbsolutePath(workspacePath, solutionId, tvNode.ID, tvNode.Extension);
                        checkInRequest.Type = CPPEI.Coolzon.Designer.Views.Models.Constant.ItemType.Resource;
                    }
                    VSFile vsFile = VSFileMgr.GetFileWithDefault(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, tvNode.ID);
                    checkInRequest.Id = tvNode.ID;
                    checkInRequest.Name = tvNode.Name;
                    checkInRequest.ParentId = tvNode.ParentID;
                    checkInRequest.SolutionId = UIContext.Current.CurrentSolution.ID;
                    checkInRequest.Version = vsFile.Version;
                    checkInRequest.FolderId = tvNode.FolderID;
                    checkInRequest.Extension = tvNode.Extension;
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        checkInRequest.Content = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    }
                    else
                    {
                        checkInRequest.Content = new System.IO.MemoryStream();
                    }
                    CPPEI.Coolzon.ServiceProxy.DesignServiceRef.CheckInResponse result = dsClient.CheckIn(checkInRequest);
                    if (result.IsSuccess)
                    {

                        tvNode.NodeStatus = NodeStatus.CheckIn;

                        // 更新本地的文件项目状态
                        VSFileMgr.GoToCheckIn(workspacePath, solutionId, tvNode.ID, tvNode.FolderID, result.ItemVersion);
                    }
                    else
                    {
                        // check in failure
                        Logger.ErrorToTag(Library.LogTAG, string.Format("check in:{0}failure", tvNode.ID));
                    }
                    progress++;

                    s_progress(tvNode.ID, tvNode.Name, progress, total);
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("签入Name:{0},Id:{1}失败,ex:{2}", tvNode.Name, tvNode.ID, ex));
                    hasError = true;
                    break;
                }
            }

            dsClient.Close();

            s_completed(hasError, progress, total);
            s_isRunning = false;
            s_thread = null;
        }
    }
}
